﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wyn.PMS.Entity.Construction
{
    public class SerialGenerator
    {
        private static Random _random = new Random((int) DateTime.Now.Ticks);
        
        private static int _idBase = 0;

        private const int _idGap = 0x100;
        
        public static readonly int _primaryKeyLength = 20;
        
        private static string CreateUniqueString(int length)
        {
            if (length <= 0) return string.Empty;

            _idBase = (_idBase + _idGap) % 0x0fffff00;

            int result = _idBase + _random.Next(0xff);

            string str = result.ToString("X").PadLeft(length, '0');

            return str.Length > length ? str.Substring(str.Length - length, length) : str;
        }
       
        public static string CreateID(string hotelId,string prefix)
        {
            int tempLength = 0;

            if (!string.IsNullOrEmpty(hotelId))
                tempLength += hotelId.Length;

            if (!string.IsNullOrEmpty(prefix))
                tempLength += prefix.Length;

            return string.Format("{0}{1}{2:yyMMdd}{3}",
                prefix,
                hotelId,
                DateTime.Today,
                CreateUniqueString(_primaryKeyLength-tempLength-6));
        }
        
        public static string CreateID(string hotelId,string prefix,DateTime keyTime,int pkLength)
        {
            int tempLength = 0;

            if (!string.IsNullOrEmpty(hotelId))
                tempLength += hotelId.Length;

            if (!string.IsNullOrEmpty(prefix))
                tempLength += prefix.Length;
            return string.Format("{0}{1}{2:yyMMdd}{3}",prefix,hotelId,keyTime,
                CreateUniqueString(pkLength-tempLength-6));
        }

    }
}
